/**
 * Copyright 2011 Steffen Kaempke
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.pennychecker.eventbus.example.controller;

import com.pennychecker.eventbus.HandlerManager;
import com.pennychecker.eventbus.example.event.EditUserEvent;
import com.pennychecker.eventbus.example.event.EditUserEventHandler;
import com.pennychecker.eventbus.example.event.UserAddedEvent;
import com.pennychecker.eventbus.example.event.UserChangedEvent;
import com.pennychecker.eventbus.example.model.User;

/**
 * There is a control class. In this class, the logic 
 * is encapsulated in order to display all users, 
 * create a new or an existing one to edit.
 * 
 * @author Steffen Kaempke mailto:sk@pennychecker.com
 *
 */
public final class EditUserController {
	private User user;
	private HandlerManager eventBus;

	/**
	 * Each controller class requires an instance of the 
	 * EventBus. This is achieved by dependency injection.
	 * 
	 * @param eventBus
	 */
	public EditUserController(HandlerManager eventBus) {
		this.eventBus = eventBus;
		registerListener();
	}

	/**
	 * Registered events, which should be listened to.
	 */
	private void registerListener() {

		/**
		 * If you want to create a new user or edit an existing, then this 
	     * listener is invoked.
		 */
		eventBus.addHandler(EditUserEvent.TYPE, new EditUserEventHandler() {

			public void onEditUserEvent(EditUserEvent event) {
				user = event.getUser();
				if (null == user) {
					createUser();
				} else {
					editUser();
				}
			}
		});
	}

	/**
	 * Simulates the editing of user data over a GUI.
	 * @param user
	 */
	private void editUser() {
		assert null != user.getId();
		user.setFirstname("Steffen");
		user.setLastname("Kaempke");
		
		eventBus.fireEvent(new UserChangedEvent(user));
	}

	/**
	 * Simulates the editing of user data over a GUI.
	 * @param user
	 */
	private void createUser() {
		final User user = new User("Sefen", "Kaempke");
		user.setId(1);

		eventBus.fireEvent(new UserAddedEvent(user));
	}

}
